package com.hzb.gulimall.product.service.impl;

import ch.qos.logback.core.util.TimeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hzb.gulimall.product.service.CategoryBrandRelationService;
import com.hzb.gulimall.product.vo.CateLog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzb.common.utils.PageUtils;
import com.hzb.common.utils.Query;

import com.hzb.gulimall.product.dao.CategoryDao;
import com.hzb.gulimall.product.entity.CategoryEntity;
import com.hzb.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryDao categoryDao;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        //1、查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //2、组装成树形的父子结构
        //2（1）、找到所有的一级分类
        List<CategoryEntity> level1Menus = categoryEntities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu) -> {
            menu.setChildren(getChildrens(menu,categoryEntities));
            return menu;
            //菜单排序
        }).sorted((menu1,menu2) ->{
            return (menu1.getSort()==null?0 : menu1.getSort() ) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {

        //TODO 检查当前的菜单是否被别的地方所引用
        categoryDao.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> catelogPaths = new ArrayList<>();
        catelogPaths = findParentsId(catelogId,catelogPaths);
        Collections.reverse(catelogPaths);
        return catelogPaths.toArray(new Long[catelogPaths.size()]);
    }

    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    @Override
    public List<CategoryEntity> getCategoryList() {

        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Override
    public Map<String, List<CateLog2Vo>> getCatalogJson() {

       return getCatalogJsonDbWithRedisLock();
    }

    //使用redisson处理分布式锁
    public Map<String, List<CateLog2Vo>> getCatalogJsonDbWithRedisson(){

        Map<String, List<CateLog2Vo>> catalogJsonForRedis=null;
        RLock lock = redisson.getLock("CatalogJson-Lock");
        lock.lock();//最佳实战是自己制定锁时间，时间长点即可
        try {
            Thread.sleep(30000);
            catalogJsonForRedis = getCatalogJsonForRedis();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            return catalogJsonForRedis;
        }
    }

    public Map<String, List<CateLog2Vo>> getCatalogJsonDbWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        ValueOperations<String, String> operations = template.opsForValue();
        Boolean lock = operations.setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock){
            Map<String, List<CateLog2Vo>> catalogJson = getCatalogJsonForRedis();
            String lockValue = operations.get("lock");
            String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                    "    return redis.call(\"del\",KEYS[1])\n" +
                    "else\n" +
                    "    return 0\n" +
                    "end";
            template.execute(new DefaultRedisScript<Long>(script,Long.class), Arrays.asList("lock"),lockValue);
            return catalogJson;
        }else {
            try{
                Thread.sleep(100);
            }catch (Exception e){
                e.printStackTrace();
            }
            return getCatalogJsonDbWithRedisLock();
        }
    }

    //TODO 产生堆外内存溢出：OutOfDirectMemoryError
    //1）、springBoot2.0以后默认使用lettuce作为操作redisde客户端。他使用netty进行网络通信；
    //2）、lettuce的bug导致netty的堆外溢出， -Xmx300m；netty如果没有指定堆外内存，默认使用 -Xmx300m
    //解决方案：不能使用-Dio.netty.maxDirectMemory只去调大堆外内存；
    //1）、升级lettuce客户端 2）、切换使用jedis
    //redisTemplate
    //lettuce/jedis操作redis的底层客户端，Spring再次封装redisTemplate
    //@Override
    public Map<String, List<CateLog2Vo>> getCatalogJsonForRedis() { //添加redis缓存

        //给缓存中放入JSON字符串，拿出的也是JSON字符串，还需要逆转为能用的对象类型

        /*
        1、空结果缓存：解决缓存穿透
        2、设置过期时间（加随机值）：解决缓存雪崩
        3、加锁：解决缓存击穿
         */
        //1、加入缓存逻辑，缓存中存的是JSON字符串
        //JSON跨语言跨平台
        String catalogJson = template.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(catalogJson)){
            //缓存中没有查询数据库
            Map<String, List<CateLog2Vo>> catalogJsonFordb = getCatalogJsonFordb();
            //查询到的数据放入缓存，将对象转换为JSON数据放入缓存中
            template.opsForValue().set("catalogJson", JSON.toJSONString(catalogJsonFordb));
            return catalogJsonFordb;
        }
        //转为我们指定的对象
        Map<String, List<CateLog2Vo>> map = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<CateLog2Vo>>>() {
        });
        return map;
    }

    //获取三级菜单
    private Map<String, List<CateLog2Vo>> getCatalogJsonFordb() {

        List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<>(null));
        List<CategoryEntity> categoryList = getCategorys(categoryEntityList,0L);
        Map<String, List<CateLog2Vo>> map = categoryList.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntities = getCategorys(categoryEntityList,v.getCatId());
            List<CateLog2Vo> parent_cid = categoryEntities.stream().map(l2 -> {
                CateLog2Vo cateLog2Vo = new CateLog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                List<CategoryEntity> catelevel3 = getCategorys(categoryEntityList,l2.getCatId());
                List<CateLog2Vo.CateLog3Vo> collect = null;
                if (catelevel3 != null) {
                    collect = catelevel3.stream().map(l3 -> {
                        CateLog2Vo.CateLog3Vo cateLog3Vo1 = new CateLog2Vo.CateLog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                        return cateLog3Vo1;
                    }).collect(Collectors.toList());
                }
                cateLog2Vo.setCatalog3List(collect);
                return cateLog2Vo;
            }).collect(Collectors.toList());
            return parent_cid;
        }));
        return map;
    }

    private List<CategoryEntity> getCategorys(List<CategoryEntity> categoryEntityList, Long catId) {
        List<CategoryEntity> collect = categoryEntityList.stream().filter(item -> item.getParentCid() == catId).collect(Collectors.toList());
        //baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
        return collect;
    }

    private List<Long> findParentsId(Long catelogId, List<Long> catelogPaths) {
        catelogPaths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0){
            findParentsId(categoryEntity.getParentCid(),catelogPaths);
        }
        return catelogPaths;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all){
        //整个这个的菜单，就是我们要用的子菜单
        List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
            //当前菜单的父ID如果等于指定的菜单的id，那么说明当前菜单就是它的子菜单
            return categoryEntity.getParentCid() == root.getCatId();
            //每一个子菜单可能还会有子菜单，包括这些子菜单还是需要排序的
        }).map(categoryEntity -> {
            //第一个参数：当前的这个菜单，第二个参数：在all里面找到categoryEntity的子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            //找到以后，将这个菜单进行返回
            return categoryEntity;
            //菜单排序
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0 : menu1.getSort() ) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        //找到子菜单，并且排好序以后，将他们收集返回
        return children;
    }

}